import React, { Component } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'

import './header.less'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import { formateDate } from '../../utils/dateUtils'
import { reqWeather } from '../../api/admin'
import menuConfig from '../../config/menuConfig.js'


import { Modal, Button } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

function myWithRouter (MessCom) {
  return (props) => {
    const location = useLocation()
    const navigate = useNavigate()
    console.log(location);
    return <MessCom {...props} location={location} navigate={navigate} />
  }
}
class Header extends Component {
  state = {
    currentTime: formateDate(Date.now()), //当前时间字符串
    weather: '' //天气的文本
  }

  getTime = () => {
    this.timer = setInterval(() => {
      const currentTime = formateDate(Date.now())
      this.setState({ currentTime })
    }, 1000)
  }

  getWeather = async () => {
    //调用接口请求异步获取数据
    const weather = await reqWeather()
    this.setState({ weather })
  }

  getTitle = () => {
    //获取当前路径的path
    const path = this.props.location.pathname
    let title
    menuConfig.forEach(item => {
      if (item.key === path) {
        title = item.title
      } else if (item.children) {
        const cItem = item.children.find(cItem => path.indexOf(cItem.key) === 0)
        if (cItem) {
          title = cItem.title
        }
      }
    })
    return title
  }

  logout = () => {
    confirm({
      title: '确定退出吗?',
      icon: <ExclamationCircleOutlined />,
      onOk: () => {
        storageUtils.removeUser()
        memoryUtils.user = {}
        this.props.navigate('/login', { replace: true })
      },
      onCancel () {
        console.log('Cancel');
      },
    });
  }

  //第一次render之后执行
  componentDidMount () {
    this.getTime()
    this.getWeather()
  }

  componentWillUnmount () {
    clearInterval(this.timer)
  }

  render () {
    const { currentTime, weather } = this.state
    const title = this.getTitle()
    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎，{memoryUtils.user.username}</span>
          <span>
            <Button type="link" onClick={this.logout}>
              退出
            </Button>
          </span>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span>{currentTime}</span>
            <span>{weather}</span>
          </div>
        </div>
      </div>
    )
  }
}

export default myWithRouter(Header)